<template>
  <div class="frame-bg">
    <el-card class="el-card">
      <el-form
        :model="newIdea"
        :rules="rules"
        ref="newIdeaForm"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="newIdea.title"
            placeholder="Enter the title"
          ></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-tag
            v-for="tag in selectedTags"
            :key="tag"
            closable
            @close="handleClose(tag)"
            >{{ tag }}</el-tag
          >
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
            >+ 新标签</el-button
          >
        </el-form-item>
        <el-form-item label="内容">
          <div style="border: 1px solid #ccc; margin-bottom: 10px">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="newIdea.content"
              :defaultConfig="editorConfig"
              @onCreated="handleCreated"
            />
          </div>
          <!-- <el-button type="primary" @click="syncHTML">提交</el-button> -->
        </el-form-item>
        <el-form-item>
          <el-space justify="end">
            <el-button type="primary" @click="submitForm(newIdeaForm)"
              >创建</el-button
            >
            <el-button @click="resetForm(newIdeaForm)">重置</el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, onBeforeUnmount, shallowRef } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import type { FormInstance, FormRules } from "element-plus";

  import "@wangeditor/editor/dist/css/style.css"; // 引入 css
  import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

  import { useRouter } from "vue-router";
  import { useUserStore } from "@/stores/user";
  import { defaultIdea, type Idea } from "@/types/idea";
  import { apiAddIdea } from "@/api/idea";
  import { dateToString, stringToDate } from "@/utils/conversion";

  const router = useRouter();
  const userStore = useUserStore();

  // 表单规则
  const rules = reactive({
    title: [
      { required: true, message: "Please input the title", trigger: "blur" },
    ],
  });

  // 新增博客的数据
  const newIdea = reactive<Idea>({
    id: 0,
    title: "",
    tags: [],
    views: 0,
    stars: 0,
    created_at: "",
    content: "",
  });

  // 标签相关的状态
  const selectedTags = ref<string[]>([]);
  const inputVisible = ref(false);
  const inputValue = ref("");

  // 处理标签关闭
  function handleClose(tag: string) {
    selectedTags.value.splice(selectedTags.value.indexOf(tag), 1);
    newIdea.tags = selectedTags.value;
  }

  // 显示输入框
  function showInput() {
    inputVisible.value = true;
    inputValue.value = "";
  }

  // 确认输入的新标签
  function handleInputConfirm() {
    let tag = inputValue.value.trim();
    if (tag) {
      selectedTags.value.push(tag);
      newIdea.tags.push(tag);
    }
    inputVisible.value = false;
    inputValue.value = "";
  }

  const newIdeaForm = ref<FormInstance>();
  const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid: boolean) => {
      if (valid) {
        newIdea.created_at = dateToString(new Date());

        try {
          const ideaId = await apiAddIdea(newIdea);
          if (ideaId !== 0) {
            router.push(`/idea?id=${ideaId}`);
          } else {
            ElMessage.error("添加失败，请重试");
          }
        } catch (err) {
          alert(err);
        }
      } else {
        ElMessage.error("添加失败，请重试");
        // return false;
      }
    });
  };

  // 重置表单
  function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return;
    formEl.resetFields();
    newIdea.title = "";
    newIdea.tags = [];
    newIdea.content = "";
    newIdea.created_at = "";
    selectedTags.value = [];
  }

  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef();

  // 模拟 ajax 异步获取内容
  onMounted(() => {
    setTimeout(() => {
      newIdea.content = "<p>请输入内容</p>";
    }, 1500);
  });

  const toolbarConfig = {};
  const editorConfig = { placeholder: "请输入内容..." };

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
  });

  const handleCreated = (editor: any) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
  };
</script>

<style scoped>
  .frame-bg {
    /* min-height: 100vh; */
    /* display: flex; */
    display: block;
    width: 80%;
    margin-left: 10%;
    margin-top: 0%;
  }

  @media (max-width: 1024px) {
    .frame-bg {
      width: 100%;
      margin-left: 0;
    }
  }

  .el-card {
    background-color: #232831;
  }

  .input-new-tag {
    width: 120px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
</style>
